<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>流程定义列表</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
    <link rel="stylesheet" th:href="@{/pear/component/luminar/css/luminar.css}">

</head>
<body class="pear-container">
<div class="layui-card">
    <div class="layui-card-body">
        <!-- Layui 标签页 -->
        <!--        <div class="layui-tab" lay-filter="simpleTabs">-->
        <!--            <ul class="layui-tab-title">-->
        <!--                <li class="layui-this">表单信息</li> &lt;!&ndash; 默认选中的标签页 &ndash;&gt;-->
        <!--                <li>流程图</li>-->
        <!--            </ul>-->
        <!--            <div class="layui-tab-content">-->
        <!--                <div class="layui-tab-item layui-show">-->
        <!--                    <div id="testdemo" style="width:60%;margin: 30px auto;padding: 30px;border: 2px solid #009688;">-->
        <!--                    -->
        <!--                    </div>-->
        <!--                </div>-->
        <!--                <div class="layui-tab-item">-->
        <!--                    <p>这是第二个标签页的内容</p>-->
        <!--                </div>-->
        <!--            </div>-->
        <!--        </div>-->

        <div id="testdemo" style="width:60%;margin: 30px auto;padding: 30px;border: 2px solid #009688;">

        </div>


    </div>
</div>


<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/pear/pear.js}"></script>
<script th:src="@{/pear/component/luminar/luminar.js}"></script>
<script th:src="@{/pear/component/luminar/js/Sortable/Sortable.js}"></script>
<script th:src="@{/pear/component/luminar/js/iceEditor/iceEditor.js}"></script>
<script th:inline="javascript">
    let baseURL = /*[[@{/}]]*/ '';
    layui.use(['formDesigner', 'form', 'layer', 'upload', 'element',], function () {
        // let tabs = layui.tabs
        let layer = layui.layer;
        let $ = layui.jquery;
        let upload = layui.upload;
        let formDesigner = layui.formDesigner;
        let form = layui.form;
        let element = layui.element;
        let render;
        let imageList = []
        let fileList = []
        let queryString = window.location.search;
        // 解析查询参数
        let urlParams = new URLSearchParams(queryString);
        let processDefinitionId = urlParams.get('processDefinitionId');
        let formId = urlParams.get('formId');
        console.log(urlParams.get("fieldData"))
        let formField = JSON.parse(urlParams.get("fieldData"))
        let formData = JSON.parse(urlParams.get("formData"))
        if (formField !== undefined) {
            render = formDesigner.render({
                elem: '#testdemo',
                data: formField,
                viewOrDesign: true,
                formData: formData
            });
            let images = render.getImages();
            let iList = []
            for (let i = 0; i < images.length / 2; i++) {
                let obj = {}
                obj['' + images[i].select] = []
                iList.push(obj)
            }
            let v = new Array(images.length / 2).fill(0);
            for (let i = 0; i < images.length / 2; i++) {
                upload.render({
                    elem: '#' + images[i].select,
                    url: baseURL + 'workflow/formData/uploadImg',
                    data: {
                        formId: formId
                    },
                    size: 500,
                    acceptMime: 'image/jpeg, image/png,image/webp',
                    multiple: true,
                    number: 3,
                    before: function (obj) {
                        layer.msg('图片上传中...', {
                            icon: 16,
                            shade: 0.01,
                            time: 0
                        })
                    },
                    done: function (res) {
                        layer.close(layer.msg());//关闭上传提示窗口
                        if (res.code === 1000) {
                            //上传完毕
                            $('#uploader-list-' + images[i].select.replace("image", "")).append(
                                `
                                <div class="file-iteme"  style="position: relative;padding: 5px">
                                    <span class="layui-badge badge " id="file-item-${v[i]++}">x</span></li>
                                    <div class="handle">
                                        <i class="layui-icon layui-icon-delete"></i>
                                    </div>
                                    <img style="width: 100px; height: 100px;" src="${baseURL}${res.data}" alt="Image">
                                </div>
                            `
                            );
                            let o = images[i].select
                            iList[i][o].push(res.data)
                            imageList = iList
                            for (let j = 0; j < v[i]; j++) {
                                $('#uploader-list-' + images[i].select.replace("image", "") + ' #file-item-' + j).on('click', function () {
                                    $(this).parent().remove();
                                    iList[i][o][j] = ""
                                });
                            }
                            return
                        }
                        return layer.msg(res.msg, {icon: 2, time: 2000});
                    }
                });
            }


            let filesData = render.getFiles();
            let fList = []
            for (let i = 0; i < filesData.length / 2; i++) {
                let obj = {}
                obj['' + filesData[i].select] = []
                fList.push(obj)
            }

            for (let i = 0; i < filesData.length / 2; i++) {
                let uploadListIns = upload.render({
                    elem: '#' + filesData[i].select
                    , elemList: $('#list-' + filesData[i].select.replace("file", "")) //列表元素对象
                    , url: baseURL + 'workflow/formData/uploadFile'
                    , data: {formId: formId}
                    , accept: 'file'
                    , exts: 'zip|rar|pdf|xlsx'
                    , size: 200 * 1024
                    , multiple: true
                    , number: 3
                    , auto: false
                    , bindAction: '#listAction-' + filesData[i].select.replace("file", "")
                    , choose: function (obj) {
                        let that = this;
                        let files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                        //读取本地文件
                        obj.preview(function (index, file, result) {
                            let tr = $(['<tr id="upload-' + index + '">'
                                , '<td>' + file.name + '</td>'
                                , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                                , '<td id="lps-' + index + '"><span id="lps-span-' + index + '" style="display:none;color: red;">1</span><div class="layui-progress"  lay-filter="progress-demo-' + index + '"><div class="layui-progress-bar" lay-percent=""></div></div></td>'
                                , '<td>'
                                , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                                , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                                , '</td>'
                                , '</tr>'].join(''));

                            //单个重传
                            tr.find('.demo-reload').on('click', function () {
                                obj.upload(index, file);
                                $('#lps-span-' + index).hide()
                                return false
                            });

                            //删除
                            tr.find('.demo-delete').on('click', function () {
                                let spanValue = tr.children().find('span').first().text(); //获取上传状态
                                if (spanValue === '') {
                                    let fileName = tr.children().first().text();
                                    for (let j = 0; j < fList[i][filesData[i].select].length; j++) {
                                        let t = fList[i][filesData[i].select][j].split("/").pop().split("_").pop()
                                        if (t === fileName) {
                                            fList[i][filesData[i].select].splice(j, 1)
                                        }
                                    }
                                    fList[i][filesData[i].select].indexOf(fileName)
                                    fileList = fList
                                }
                                delete files[index]; //删除对应的文件
                                tr.remove();
                                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                                return false
                            });
                            that.elemList.append(tr);
                            element.render('progress'); //渲染新加的进度条组件
                        });
                    }
                    , done: function (res, index, upload) { //成功回调
                        let that = this;
                        if (res.code === 1000) { //上传成功
                            delete this.files[index]; //删除文件队列已经上传成功的文件
                            $('#lps-span-' + index).text('')
                            let o = filesData[i].select
                            fList[i][o].push(res.data)
                            fileList = fList
                            return;
                        }
                        this.error(index, upload, res.msg);
                    }
                    , allDone: function (obj) { //多文件上传完毕后的状态回调
                        console.log(obj)
                    }
                    , error: function (index, upload, msg) { //错误回调
                        let that = this;
                        let tr = that.elemList.find('#upload-' + index)
                            , tds = tr.children();
                        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
                        $('#lps-span-' + index).show()
                        $('#lps-span-' + index).text(msg + '.')
                        element.progress('progress-demo-' + index, 0 + '%');
                    }
                    , progress: function (n, elem, e, index) {
                        element.progress('progress-demo-' + index, n + '%'); //执行进度条。n 即为返回的进度百分比
                    }
                });
            }

        }

        //监听提交
        form.on('submit(demo1)', function (data) {
            let formData = render.getFormData();
            if (imageList.length > 0) {
                // 处理数据，移除空字符串
                formData.imgFile = imageList.map(item => {
                    const key = Object.keys(item)[0]; // 获取键名
                    const filteredArray = item[key].filter(url => url.trim() !== ''); // 移除空字符串
                    return {[key]: filteredArray}; // 返回新的对象
                });
            }
            if (fileList.length > 0) {
                formData.files = fileList;
            }
            let signs = render.getSign()
            if (signs.length > 0) {
                formData.signs = signs;
            }
            let jsonString = JSON.stringify(formData);
            let temp = {
                "formId": formId,
                "formData": jsonString,
                "processDefinitionId": processDefinitionId
            }
            let loading = layer.msg('正在提交...', {
                icon: 16,
                shade: 0.01,
                time: 0
            });
            $.ajax({
                url: baseURL + 'workflow/processFrom/addFormData',
                data: JSON.stringify(temp),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {
                    layer.close(loading);
                    if (result.code === 1000) {
                        layer.msg(result.msg, {
                            icon: 1,
                            time: 1000
                        }, function () {
                            window.location.href = `process_definition_list.html`
                        });
                    } else {
                        layer.msg(result.msg, {
                            icon: 2,
                            time: 1000
                        });
                    }
                },
                error: function () {
                    layer.close(loading);
                    layer.msg('服务器错误，请稍后再试！', {
                        icon: 2,
                        time: 1000
                    });
                }
            });
            return false;
        });

    });

</script>


</body>
</html>